<template>
  <div>
      <a-button id="new" @click="handleAdd">导入学生</a-button>
      <a-modal v-model="visible" title="导入学生" ok-text="确认" cancel-text="取消"  @ok="handleSubmit">
        <div class="container">
          {{ upload_file || "导入学生" }}
          <input
            type="file"
            accept=".xls,.xlsx"
            class="upload_file"
            @change="readExcel($event)"
          />
        </div>
        </a-modal>
  </div>
</template>

<script>
  import { request } from "../../api/index";
  import XLSX from "xlsx";
  export default {
    name: 'classAdd',
    data () {
      return {
        form: this.$form.createForm(this),
        upload_file: "",
        lists: [],
        visible : false,
      }
    },
    methods: {
      value(){
        this.form.setFieldsValue({
          id:this.values.id,
          name:this.values.name,
        })
      },
      handleSubmit (e) {
        this.visible = false;
        // console.log(this.lists)
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (!err) {
            this.values = values;
            request({
              url: "/user/student_import",
              method: "post",
              data: {
                list:this.lists
              },
            })
              .then((res) => {
                if(res.data.message == "success"){
                  alert("添加成功")
                  this.$parent.refreshS()
                }else{
                  alert("添加失败")
                }
              })
              .catch((err) => {
                // console.log(err)
              });
          }
        })
      },
      handleAdd() {
        this.visible = true;
      },
      readExcel(e) {
        // 读取表格文件
        let that = this;
        const files = e.target.files;
        if (files.length <= 0) {
          return false;
        } else if (!/.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
          this.$message({
            message: "上传格式不正确，请上传xls或者xlsx格式",
            type: "warning"
          });
          return false;
        } else {
          // 更新获取文件名
          that.upload_file = files[0].name;
        }
        const fileReader = new FileReader();
        fileReader.onload = ev => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: "binary"
            });
            const sheet2JSONOpts = { defval: ''}
            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname],{raw:false}); //生成json表格内容
            that.lists = [];
            // 从解析出来的数据中提取相应的数据
            ws.forEach(item => {
              that.lists.push({
                person_id: item["学号"],
                name: item["姓名"],
                sex: item["性别"],
                class_id: item["班号"],
                birthday: item["生日"]
              });
            });
          } catch (e) {
            return false;
          }
        };
        fileReader.readAsBinaryString(files[0]);
      }
    },
    
  }
</script>
<style scoped>
  #new{
    margin-left:5px;
    float: left;
  }
</style>